package neu.soft.facade;

import lombok.extern.slf4j.Slf4j;
import neu.soft.binder.ChannelBinder;
import neu.soft.entity.OperationPurchaseOrder;
import neu.soft.exception.AppException;
import neu.soft.exception.AppExceptionCodeMsg;
import neu.soft.service.SupplyService;
import neu.soft.vo.MsgBean;
import org.apache.rocketmq.common.message.MessageConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import org.springframework.util.MimeTypeUtils;

@Component
@Slf4j
public class MessageSendHandler {

    @Autowired
    SupplyService supplyService;

    @Autowired
    ChannelBinder channelBinder;

    public boolean sendPurchaseToWarehouse(Integer purchaseOrderId) {
        OperationPurchaseOrder operationPurchaseOrder = supplyService.findById(purchaseOrderId);
        if (operationPurchaseOrder == null) {
            throw new AppException(AppExceptionCodeMsg.QUERY_FAIL);
        }
        MessageBuilder<MsgBean<OperationPurchaseOrder>> builder = MessageBuilder.withPayload(new MsgBean<OperationPurchaseOrder>(operationPurchaseOrder, "购货已确认，等待入库"))
                .setHeader(MessageConst.PROPERTY_DELAY_TIME_LEVEL, 0)
                .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON);
        Message<MsgBean<OperationPurchaseOrder>> message = builder.build();
        log.info("消息发送成功！等待消费");
        return channelBinder.warehouseOutput().send(message);
    }
}
